<template>
  <div>
    <el-form label-width="90px" label-position="left" size="small">
      <div class="p-[10px]">
        <el-form-item label="ID">
          <span>{{ store.currentPen.id }}</span>
        </el-form-item>
        <el-form-item label="名称">
          <!-- <span>{{ store.currentPen.name }}</span> -->
          <el-input v-model="store.currentPen.name" placeholder="请输入名称" />
        </el-form-item>
      </div>
      <!-- {{store.currentPen.calculative.name}} -->
      <el-collapse v-model="activeName">
        <el-collapse-item name="realTimeData" title="实时数据"
          v-if="realTimeList.includes(store.currentPen?.calculative?.name)">
          <div class="p-[10px]" v-if="store.currentPen?.calculative?.name == 'text'">
            <el-form-item label="建筑">
              <buildingSelect class="w-full" v-model="realTimeData.buildingId" :project-id="projectId"
                placeholder="请选择建筑" @change="realTimeDataChange('buildingId')" />
            </el-form-item>
            <el-form-item label="楼层">
              <drawingSelect class="w-full" v-model="realTimeData.drawingId" :project-id="projectId"
                :building-id="realTimeData.buildingId"
                :disabled="!realTimeData.buildingId || realTimeData.buildingId == -1" placeholder="请选择楼层"
                @change="realTimeDataChange('drawingId')" />
            </el-form-item>
            <el-form-item label="设备">
              <deviceSelect class="w-full" v-model="realTimeData.device" :project-id="projectId"
                :drawing-id="realTimeData.drawingId || -1"
                :disabled="!realTimeData.drawingId && realTimeData.buildingId != -1" placeholder="请选择设备"
                @change="realTimeDataChange('device')" />
            </el-form-item>
            <el-form-item label="字段">
              <fieldSelect class="w-full" v-model="realTimeData.field" :project-id="projectId"
                :product-id="realTimeData.device?.productId" placeholder="请选择字段" :disabled="!realTimeData.device"
                @change="realTimeDataChange('field')" />
            </el-form-item>
          </div>
          <div class="p-[10px]" v-if="store.currentPen?.calculative?.name == 'echarts'">
            <el-form-item label="数据源">
              <echartsSelect class="w-full" v-model="realTimeData.echarts" :echartsName="store?.currentPen?.echarts?.name" :project-id="projectId" placeholder="请选择数据源"
                @change="realTimeDataChange('echarts')" />
            </el-form-item>
            <div v-if="store.currentPen?.echarts?.name == 'dashboardChart'">
              <el-form-item label="最小值">
                <el-input-number v-model="realTimeData.min" @change="realTimeDataChange('echarts')" />
              </el-form-item>
              <el-form-item label="最大值">
                <el-input-number v-model="realTimeData.max" @change="realTimeDataChange('echarts')" />
              </el-form-item>
            </div>
          </div>
          <div class="p-[10px]" v-if="store.currentPen?.calculative?.name == 'table'">
            <el-form-item label="数据源">
              <tableSelect class="w-full" v-model="realTimeData.table" :project-id="projectId" placeholder="请选择数据源"
                @change="realTimeDataChange('table')" />
            </el-form-item>
          </div>
          <div class="p-[10px]" v-if="store.currentPen?.calculative?.name == 'video'">
            <el-form-item label="建筑">
              <buildingSelect class="w-full" v-model="realTimeData.buildingId" :project-id="projectId"
                placeholder="请选择建筑" @change="realTimeDataChange('buildingId')" />
            </el-form-item>
            <el-form-item label="楼层">
              <drawingSelect class="w-full" v-model="realTimeData.drawingId" :project-id="projectId"
                :building-id="realTimeData.buildingId"
                :disabled="!realTimeData.buildingId || realTimeData.buildingId == -1" placeholder="请选择楼层"
                @change="realTimeDataChange('drawingId')" />
            </el-form-item>
            <el-form-item label="监控">
              <videoSelect class="w-full" v-model="realTimeData.video" :project-id="projectId"
                :drawing-id="realTimeData.drawingId || realTimeData.buildingId" placeholder="请选择监控"
                @change="realTimeDataChange('video')" />
            </el-form-item>
          </div>
        </el-collapse-item>
        <el-collapse-item name="eventsData" title="事件数据" v-if="!noEvents.includes(store.currentPen?.calculative?.name)">
          <template #title>
            <div class="w-full flex-bc">
              事件数据
              <el-button class="!h-[20px] mr-[10px]" type="primary" :icon="Plus"
                @click.stop="addEventsData">添加</el-button>
            </div>
          </template>
          <el-collapse>
            <el-collapse-item v-for="(item, index) in eventsData" :title="`数据${index + 1}`" :key="index">
              <template #title>
                <div class="w-full flex-bc">
                  数据 {{ index + 1 }}
                  <el-button class="!h-[20px] mr-[10px]" type="primary" :icon="Delete"
                    @click.stop="deleteEventsData(item)"></el-button>
                </div>
              </template>
              <div class="p-[10px]">
                <el-form-item label="建筑">
                  <buildingSelect class="w-full" v-model="item.buildingId" :project-id="projectId" placeholder="请选择建筑"
                    @change="eventsDataChange('buildingId', item)" />
                </el-form-item>
                <el-form-item label="楼层">
                  <drawingSelect class="w-full" v-model="item.drawingId" :project-id="projectId"
                    :building-id="item.buildingId" :disabled="!item.buildingId || item.buildingId == -1"
                    placeholder="请选择楼层" @change="eventsDataChange('drawingId', item)" />
                </el-form-item>
                <el-form-item label="设备">
                  <deviceSelect class="w-full" v-model="item.device" :project-id="projectId"
                    :drawing-id="item.drawingId || -1" :disabled="!item.drawingId && item.buildingId != -1"
                    placeholder="请选择设备" @change="eventsDataChange('device', item)" />
                </el-form-item>
                <el-form-item label="字段">
                  <fieldSelect class="w-full" v-model="item.field" :project-id="projectId"
                    :product-id="item.device?.productId" placeholder="请选择字段" :disabled="!item.device"
                    @change="eventsDataChange('field', item)" />
                </el-form-item>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-collapse-item>
        <el-collapse-item name="controlCommand" title="控制命令"
          v-if="!noEvents.includes(store.currentPen?.calculative?.name)">
          <template #title>
            <div class="w-full flex-bc">
              控制命令
              <el-button class="!h-[20px] mr-[10px]" type="primary" :icon="Plus"
                @click.stop="addControlCommand">添加</el-button>
            </div>
          </template>
          <el-collapse>
            <el-collapse-item v-for="(item, index) in controlCommand" :title="`命令${index + 1}`" :key="index">
              <template #title>
                <div class="w-full flex-bc">
                  <div v-if='!item?.editName'>{{ item.commandName }}</div>
                  <el-input v-else class="flex-1" v-model="item.commandName" placeholder="请设置命令名称" autofocus @click.stop
                    @blur="item.editName = false" />
                  <div @click.stop>
                    <el-button class="!h-[20px] mx-[5px]" type="primary" :icon="Edit"
                      @click="item.editName = true"></el-button>
                    <el-button class="!h-[20px] mr-[10px]" type="primary" :icon="Delete"
                      @click="deleteControlCommand(item)"></el-button>
                  </div>
                </div>
              </template>
              <div class="p-[10px]">
                <el-form-item label="建筑">
                  <buildingSelect class="w-full" v-model="item.buildingId" :project-id="projectId" placeholder="请选择建筑"
                    @change="controlCommandChange('buildingId', item)" />
                </el-form-item>
                <el-form-item label="楼层">
                  <drawingSelect class="w-full" v-model="item.drawingId" :project-id="projectId"
                    :building-id="item.buildingId" :disabled="!item.buildingId || item.buildingId == -1"
                    placeholder="请选择楼层" @change="controlCommandChange('drawingId', item)" />
                </el-form-item>
                <el-form-item label="设备">
                  <deviceSelect class="w-full" v-model="item.device" :project-id="projectId"
                    :drawing-id="item.drawingId || -1" :disabled="!item.drawingId && item.buildingId != -1"
                    placeholder="请选择设备" @change="controlCommandChange('device', item)" />
                </el-form-item>
                <el-form-item label="命令">
                  <commandSelect class="w-full" v-model="item.command" :project-id="projectId"
                    :product-id="item.device?.productId" placeholder="请选择命令" :disabled="!item.device"
                    @change="controlCommandChange('command', item)" />
                </el-form-item>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-collapse-item>
      </el-collapse>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { useTopologyEditorStore } from '@/store/modules/topology-editor'
import { EventAction, type Event } from '@meta2d/core'
import buildingSelect from './components/buildingSelect.vue'
import drawingSelect from './components/drawingSelect.vue'
import deviceSelect from './components/deviceSelect.vue'
import fieldSelect from './components/fieldSelect.vue'
import echartsSelect from './components/echartsSelect.vue'
import tableSelect from './components/tableSelect.vue'
import videoSelect from './components/videoSelect.vue'
import commandSelect from './components/commandSelect.vue'
import { Plus, Delete, Edit } from "@element-plus/icons-vue";
declare interface CustomEvent extends Event {
  setProps: Array<{ key: string | undefined; value: string | undefined, formOption: any }> | null
}
declare const window: any // eslint-disable-line
defineOptions({
  name: 'EditorPropsPenData'
})
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({})
  }
})
const noEvents = ref(['echarts', 'table', 'video'])
const realTimeList = ref(['text', 'echarts', 'table', 'video'])
const emit = defineEmits(['update:visible', 'update:data'])
const projectId = useRoute().query.projectId as string
const store = ref(useTopologyEditorStore())
const activeName = ref(['realTimeData', 'eventsData', 'controlCommand'])
const realTimeData = computed({
  get: () => {
    if (!store.value.currentPen?.realTimeData) {
      store.value.currentPen.realTimeData = {
        buildingId: null,
        drawingId: null,
        device: null,
        field: null,
        echarts: null,
        min: 0,
        max: 100,
        table: null,
        video: null
      }
    }
    return store.value.currentPen.realTimeData
  },
  set: () => { }
})
const eventsData = computed({
  get: () => {
    if (!store.value.currentPen?.eventsData) {
      store.value.currentPen.eventsData = []
    }
    return store.value.currentPen.eventsData
  },
  set: () => { }
})
const controlCommand = computed({
  get: () => {
    if (!store.value.currentPen?.controlCommand) {
      store.value.currentPen.controlCommand = []
    }
    return store.value.currentPen.controlCommand
  },
  set: () => { }
})
onMounted(() => {

})
const addEventsData = () => {
  store.value.currentPen.eventsData.push({
    id: `${Date.now() + Math.round(Math.random() * 10000)}`,
    buildingId: null,
    drawingId: null,
    device: null,
    field: null,
  })
}
const deleteEventsData = (row) => {
  store.value.currentPen.form = store.value.currentPen?.form?.filter((item) => item.key != `events-${row.id}`)
  store.value.currentPen.eventsData = store.value.currentPen?.eventsData?.filter((item) => item.id != row.id)
}
const addControlCommand = () => {
  store.value.currentPen.controlCommand.push({
    id: `${Date.now() + Math.round(Math.random() * 10000)}`,
    commandName: `命令${store.value.currentPen.controlCommand.length + 1}`,
    buildingId: null,
    drawingId: null,
    device: null,
    command: null,
  })
}
const deleteControlCommand = (row) => {
  store.value.currentPen.controlCommand = store.value.currentPen.controlCommand.filter((item) => item.id != row.id)
}
const realTimeDataChange = (key) => {
  switch (key) {
    case 'buildingId':
      realTimeData.value.drawingId = null
      realTimeData.value.device = null
      realTimeData.value.field = null
      realTimeData.value.video = null
      setForm('text')
      break
    case 'drawingId':
      realTimeData.value.device = null
      realTimeData.value.field = null
      realTimeData.value.video = null
      setForm('text')
      break
    case 'device':
      realTimeData.value.field = null
      setForm('text')
      break
    case 'field':
      setForm("text", {
        dataId: `data-${projectId}-${realTimeData.value.device?.id}-${realTimeData.value.field?.fieldAlias}`,
        name: `${realTimeData.value.device?.deviceName}-${realTimeData.value.field?.fieldName}`,
      })
      break
    case 'echarts':
      window.meta2d.setValue({
        id: store.value.currentPen.id,
        tags: [realTimeData.value.echarts?.dataIdx],
      });
      if (store.value.currentPen.echarts.name == "lineChart" || store.value.currentPen.echarts.name == "barChart") {
        // window.meta2d.setValue({
        //   id: store.value.currentPen.id,
        //   dataX: realTimeData.value.echarts.dataIds.map(item => item.name),
        // });
        // setForm("dataX", { dataId: realTimeData.value.echarts?.dataIdx})

      } else if (store.value.currentPen.echarts.name == "pieChart") {
        window.meta2d.setValue({
          id: store.value.currentPen.id,
          dataY: realTimeData.value.echarts.dataIds.map(item => { return { name: item.name, value: 0 } }),
        });
      } else if (store.value.currentPen.echarts.name == "dashboardChart") {
        store.value.currentPen.echarts.option.series[0].name = realTimeData.value.echarts?.name
        store.value.currentPen.echarts.option.series[0].data = realTimeData.value.echarts?.dataIds?.map((item, index) => {
          return {
            name: item.name,
            value: 0,
          }
        })
        window.meta2d.setValue({
          id: store.value.currentPen.id,
          'echarts.option.series.0.min': realTimeData.value.min,
          'echarts.option.series.0.max': realTimeData.value.max
        }, { render: true, history: true })
      }
      setForm("dataY", realTimeData.value.echarts?.dataIds)
      break
    case 'table':
      setForm('data', realTimeData.value.table)
      break
    case 'video':
      window.meta2d.setValue({
        id: store.value.currentPen.id,
        video: realTimeData.value?.video?.monitorUrl
        // video: 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm'
      })
      window.meta2d.render()
      break
  }
}
const eventsDataChange = (key, item) => {
  switch (key) {
    case 'buildingId':
      item.drawingId = null
      item.device = null
      item.field = null
      setForm(`events-${item.id}`)
      break
    case 'drawingId':
      item.device = null
      item.field = null
      setForm(`events-${item.id}`)
      break
    case 'device':
      item.field = null
      setForm(`events-${item.id}`)
      break
    case 'field':
      setForm(`events-${item.id}`, {
        dataId: `data-${projectId}-${item.device?.id}-${item.field?.fieldAlias}`,
        name: `${item.device?.deviceName}-${item.field?.fieldName}`,
      })
      break
  }
}
const controlCommandChange = (key, item) => {
  switch (key) {
    case 'buildingId':
      item.drawingId = null
      item.device = null
      item.command = null
      break
    case 'drawingId':
      item.device = null
      item.command = null
      break
    case 'device':
      item.command = null
      break
    case 'command':
      break
  }
}
const setForm = (key, dataIds = null) => {
  if (!store.value.currentPen.form) {
    store.value.currentPen.form = [
      {
        key: key,
        dataIds: dataIds,
      },
    ]
  } else {
    store.value.currentPen.form = store.value.currentPen.form.filter((item) => item.key !== key)
    store.value.currentPen.form.push({
      key: key,
      dataIds: dataIds,
    })
  }
  window.meta2d.initBindDatas();
}
</script>

<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  background-color: transparent;
  padding: 0 10px;
  position: relative;
}

.collapse-delete-icon {
  position: absolute;
  right: 35px;
  top: 0;

  &:hover {
    color: #409eff;
  }
}

.props-icon {
  width: 30px !important;
}

.set-props-wrapper {
  margin-bottom: 18px;

  .set-props-header {
    height: 36px;
    font-size: 12px;
    line-height: 36px;
    display: flex;
    justify-content: center;
    align-items: center;

    .column {
      flex: 1;
      text-align: center;
      font-size: 14px;
      color: #afafaf;
    }

    .icon {
      flex: 0 30px;
      width: 0;
      font-size: 14px;
      color: #fff;
      text-align: center;
      cursor: pointer;

      &:hover {
        color: #409eff;
      }
    }
  }

  .set-props-content {
    .row {
      //display: flex;
      //justify-content: center;
      //align-items: center;
      display: grid;
      grid-template-columns: 2fr 2fr 0fr;
      grid-gap: 5px;
      // justify-items: center;
      margin-bottom: 2px;

      .row-input {
        flex: 1;

        :deep(.el-input__inner) {
          border: 0;
        }

        &+.row-input {
          margin-left: 2px;
        }
      }

      .icon {
        flex: 0 30px;
        width: 0;
        font-size: 14px;
        color: #fff;
        text-align: center;
        cursor: pointer;

        &:hover {
          color: #409eff;
        }
      }
    }
  }
}
</style>
